package com.example.edianzu.somur.login.mvp.view;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.AppCompatTextView;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import com.example.edianzu.somur.App;
import com.example.edianzu.somur.MainActivity;
import com.example.edianzu.somur.R;
import com.example.edianzu.somur.api.APIConstants;
import com.example.edianzu.somur.api.bean.LoginInfo;
import com.example.edianzu.somur.api.manager.APIManager;
import com.example.edianzu.somur.login.activity.FindPasswordActivity;
import com.example.edianzu.somur.login.activity.NewUserLoginActivity;
import com.example.edianzu.somur.login.mvp.presenter.ILoginPresenter;
import com.example.edianzu.somur.login.mvp.presenter.LoginPresenterImpl;
import com.example.edianzu.somur.utils.content.ValidateUtils;
import com.example.edianzu.somur.utils.manager.ActivityManager;
import com.umeng.analytics.MobclickAgent;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;

public class LoginActivity extends AppCompatActivity implements IView {

    @BindView(R.id.loginActivity_editText_phoneName)
    AppCompatEditText loginActivityEditTextPhoneNumber;
    @BindView(R.id.loginActivity_editText_passWord)
    AppCompatEditText loginActivityEditTextPassWord;
    @BindView(R.id.loginActivity_Button_login)
    AppCompatButton loginActivityButtonLogin;
    @BindView(R.id.loginActivity_ImageView_back)
    AppCompatButton loginActivityImageViewBack;
    @BindView(R.id.loginActivity_TextView_findPassword)
    AppCompatTextView loginActivityTextViewFindPassword;
    @BindView(R.id.loginActivity_TextView_newUserLogin)
    AppCompatTextView loginActivityTextViewNewUserLogin;
    private SharedPreferences sharedPreferences;
    private ILoginPresenter iLoginPresenter;

    /*18640518119
     密码123456*/

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
//        隐藏StatusBar
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);

        ActivityManager.addActivity(this);

        sharedPreferences = App.getApp().getSharedPreferences();

        //第二次
        final String phone = sharedPreferences.getString("phone", "");
        final String password = sharedPreferences.getString("password", "");
//        loginActivityEditTextPhoneNumber.setText(phone);
//        loginActivityEditTextPassWord.setText(password);

//        if (getIntent().getStringExtra("RevisePasswordActivity") != null) {
//
//            loginActivityEditTextPhoneNumber.setText(null);
//            loginActivityEditTextPassWord.setText(null);
//        }

//        if (!TextUtils.isEmpty(phone)&&!TextUtils.isEmpty(password)) {
//
//            checklLogin();
//        }

        iLoginPresenter = new LoginPresenterImpl(this);

//        loginActivityEditTextPhoneNumber.setText("18640518119");
//        loginActivityEditTextPassWord.setText("123456");

//        loginActivityButtonLogin.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {

//                iLoginPresenter.login();
//                iLoginPresenter.clear();

//                checkLogin();

//                if (!TextUtils.isEmpty(phone)&&!TextUtils.isEmpty(password)) {
//
//                    checklLogin();
//                }else {
//
//                    checklLogin();
//                }
//            }
//        });

        loginActivityImageViewBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                finish();
            }
        });

    }

    @OnClick({R.id.loginActivity_Button_login,R.id.loginActivity_TextView_findPassword, R.id.loginActivity_TextView_newUserLogin})
    public void onViewClicked(View view) {

        Intent intent=new Intent();
        switch (view.getId()) {
            case R.id.loginActivity_Button_login:

                iLoginPresenter.login();
                break;
            case R.id.loginActivity_TextView_findPassword:

                intent.setClass(this, FindPasswordActivity.class);
                startActivity(intent);
                break;
            case R.id.loginActivity_TextView_newUserLogin:

                intent.setClass(this, NewUserLoginActivity.class);
                startActivity(intent);
                break;
        }
    }

    private void checkLogin() {
        //              第一次开始检查登录
        final String phoneNumber = getPhoneNumber();
        final String passWord = getPassWord();

        if (passWord != null && phoneNumber != null) {
            if (phoneNumber.length() == 11 && ValidateUtils.isMobileNO(phoneNumber)) {

                APIManager.getApiManagerInstance().getLoginInfo(new Observer<LoginInfo>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull LoginInfo loginInfo) {

//                        Log.d("onCreate", "onNext: "+loginInfo.getData().getCompany_id()+"```````````````"+loginInfo.getData().getMobile());

                        if (loginInfo.getStatus() == 200) {

                            SharedPreferences.Editor editor = sharedPreferences.edit();
                            editor.putString("phone", phoneNumber);
                            editor.putString("password", passWord);
                            editor.putString("company_id", loginInfo.getData().getCompany_id());
                            editor.commit();

                            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                            intent.putExtra("member_id", loginInfo.getData().getMember_id());
                            intent.putExtra("login", loginInfo);

                            startActivity(intent);

                            finish();
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {

                        loginError();
                    }

                    @Override
                    public void onComplete() {

                    }
                }, phoneNumber, passWord, APIConstants.COMPANY_ID);

              /*  StringRequest stringRequest=new StringRequest(Request.Method.POST, APIRequest.LOGIN_URL, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        LoginInfo loginInfo = JSON.parseObject(response, LoginInfo.class);
                        Log.d("onResponse", "onResponse: "+ loginInfo);
                        if (loginInfo.getStatus()==200) {

                            SharedPreferences.Editor editor = sharedPreferences.edit();
                            editor.putString("phone", phoneNumber);
                            editor.putString("password", passWord);
                            editor.commit();

                            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                            intent.putExtra("member_id", loginInfo.getData().getMember_id());
                            intent.putExtra("login", loginInfo);

                            startActivity(intent);

                            finish();
                        }

//                        Toast.makeText(LoginActivity.this, loginInfo.getMsg(), Toast.LENGTH_SHORT).show();

                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {


                        loginError();
                    }
                }){
                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {

                        HashMap<String,String> hashMap=new HashMap<String, String>();
                        hashMap.put("username",phoneNumber);
                        hashMap.put("password",passWord);
                        hashMap.put("company_id","7c5be769f7854d9b97205794b276673d");
                        return hashMap;
                    }
                };

                stringRequest.setTag("login");
                requestQueue.add(stringRequest);*/
            } else {

                loginError();
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public LoginActivity getLoginActivity() {
        return this;
    }

    @Override
    public String getPhoneNumber() {
        return loginActivityEditTextPhoneNumber.getText().toString();
    }

    @Override
    public String getPassWord() {
        return loginActivityEditTextPassWord.getText().toString();
    }

    @Override
    public void loginSuccess() {

        startActivity(new Intent(this, MainActivity.class));
    }

    @Override
    public void loginError() {

        Toast.makeText(this, "登录信息有误，请确认后再次登录！！！", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void clearPhoneNumber() {

        loginActivityEditTextPhoneNumber.setText("");
    }

    @Override
    public void clearPassWord() {

        loginActivityEditTextPassWord.setText("");
    }

    //记录用户首次点击返回键的时间
    private long firstTime = 0;

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
            long secondTime = System.currentTimeMillis();
            if (secondTime - firstTime > 2000) {
                Toast.makeText(LoginActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                firstTime = secondTime;
                return true;
            } else {
//                System.exit(0);
//                killProcess(myPid());
                ActivityManager.finishAll();
            }
        }
        return super.onKeyUp(keyCode, event);
    }
}
